/* 
* Copyright (C) 2015,中油瑞飞, 
* All Rights Reserved 
* Description: TODO What the class does.   
* 
* @project 瑞信
* @author  Administrator
* @date    2016年9月22日-上午12:26:22
*
* Modification History: 
**********************************************************
* Date		  Author		    Comments
* 2016年9月22日	  Administrator			Create
**********************************************************
*/
package com.liuhaozzu.hibernate.demo.filter;

import static org.hamcrest.CoreMatchers.nullValue;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.liuhaozzu.hibernate.demo.utils.HibernateUtils;

/**
 * TODO What the class does
 * <p>Title:com.liuhaozzu.hibernate.demo.filter.OpenSessionInView.java</p>
 * <p>Description: </p>
 * <p>Company:www.richfit.com</p>
 * @author liuhaozzu
 * @date   2016年9月22日-上午12:26:22
 *
 */
public class OpenSessionInView implements Filter{

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		Session session;
		Transaction tx = null;
		try {
			session = HibernateUtils.getSession();
			tx=session.beginTransaction();
			
			chain.doFilter(request, response);
			
			tx.commit();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			if (tx!=null) {
				tx.rollback();
			}
		} finally {
			HibernateUtils.closeSession();
		}
	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#destroy()
	 */
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}
